package com.yunhe.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.yunhe.bean.OrderInfo;
import com.yunhe.bean.UserAddressInfo;
import com.yunhe.inter.OrderInfoInter;
import com.yunhe.util.SqlSessionFactoryUtil;

/**
 * 主要用来处理在购物车点击购买的所有业务
 */
@WebServlet("/ShoppingResult_2")
public class ShoppingResult_2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public ShoppingResult_2() {
        super();
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//在进行调用存储过程之前先将地址信息入库
		String address = request.getParameter("address");
		String addressString="" ;
		if(address!=null){
			 addressString = new String(address.getBytes("ISO-8859-1"),"UTF-8");
			
		}
		
		UserAddressInfo uai= new UserAddressInfo();
		//放入地址信息
		uai.setDetailedAddress(addressString);
		//放入用户id
		uai.setUserID(1);
		//获取数据库连接
		SqlSession sqlSession =SqlSessionFactoryUtil.openSqlSession();
		OrderInfoInter oiMapper = sqlSession.getMapper(OrderInfoInter.class);
		//进行地址信息入库
		oiMapper.addAddressInfo(uai);
		
		//创建订单对象
		OrderInfo oi = new OrderInfo();
		//得到购物车中所有商品ID （拼接字符串方式获取）
		String commodityIDS = request.getParameter("commodityIDS");
		//通过split（）以逗号为分割切割字符串得到数组
		String commodityIDSArray [] =commodityIDS.split(",");
		/**
		 * 循环遍历数组，循环调用存储来实现业务处理
		 */
		//生成订单号，用来解决购物车中所有的购买的商品生成同一个订单号
		Date currentTime = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = sdf.format(currentTime);
		//当前时间戳加上用户ID，暂时用ID=1，合并后从session中获取
		String orderSerialNumber =dateString+"1";
		
		for (String commID : commodityIDSArray) {
			oi.setCommodityID(Integer.parseInt(commID));
			oi.setUserID(1);
			oi.setOrderSerialNumber(orderSerialNumber);
			oiMapper.addOrderInfoByPro(oi);
			
		}
		response.sendRedirect("/easyBuy170601/shopping-result.html");
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
